let sortWeightId = "frm-lose-weight";
//type:0:称重；1:报损
let sortTyp = 1;
$(document).ready(function () {
    $('.merger-title').hide();
    $('[data-toggle="tooltip"]').tooltip();
    //报损显示弹窗
    $('#frm-lose-model').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // 触发事件的按钮
        var recipient = button.data('whatever'); // 解析出data-whatever内容
        if (recipient) {
            var modal = $(this);
            modal.find('.modal-title').text('Message To ' + recipient);
            modal.find('.modal-body input').val(recipient);
        }
    });

    //报损隐藏弹窗
    $('#frm-lose-model').on('hide.bs.modal', function (event) {
        $('#goods-detail-id').val("");
        $('#frm-lose-weight').val("");
        $('#frm-lose-select').selectpicker('val', ['noneSelectedText']);
    });

    //报损下拉
    // $('#frm-lose-select').selectpicker('render');
    $("#frm-lose-select").on("changed.bs.select", function (e) {
        let temp = $(this).val();
        $('#goods-detail-id').val(temp);
    });
});

function storageDoneCallBack(data, cancel, opt) {
    if (!cancel) {
        const obj = data.data;
        delResponseFromWcs(data, opt);
        if (obj.code == 0) {
        } else {
        }
    }
}

//回调处理
function weighRespCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    console.log(">>>>>>>>>>称重回调");
    if (cancel) {
        //todo 隐藏操作按钮等之类的
        $("#empty-btn").hide();
    } else {
        const obj = data.data;
        delResponseFromWcs(data, opt);
        if (obj.code == 0) {
        } else {
            $('#message-content').text(obj.msg);
            setTimeout("$('#message-content').text('')", 5000);
        }

    }
}

//发送指令响应回调
function wcsToWmsResponseCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    if (cancel) {
        //todo 隐藏操作按钮等之类的
        // dealWithError("emptyNumber",'');
    } else {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        console.log("KKKKKK:" + JSON.stringify(obj));
        if (obj.code == 1) {

        } else {

        }
        setTimeout("$('#message-content').text('')", 7000);
    }
}

//分拣称重
function sortWeightCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    console.log("分拣称重响应：" + JSON.stringify(data));
    if (!cancel) {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        if (obj.code == 0) {
        } else {
            $('#message-content').text(obj.msg);
            setTimeout("$('#message-content').text('')", 5000);
        }
    }
}

//货箱离开库位
function leaveBufferPosCallBack(data, cancel, opt) {

    if (!data) {
        return;
    }
    console.log("入库离开缓存位响应：" + JSON.stringify(data));
    if (!cancel) {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        if (obj.code == 0) {
        } else {
            BootstrapDialog.alert(obj.msg);
        }
    }
}

let actTemperatureCode;

//出库到缓存位
function inBufferPosCallBack(data, cancel, opt) {
    if (!data) {
        merge(true, 0);
        return;
    }
    if (!cancel) {
        //todo 逻辑处理
        const obj = data.data;
        console.log("ooooooooooooo:" + JSON.stringify(obj));
        if (obj.code == 0) {

        } else {
            delResponseFromWcs(data, opt);
        }

    } else {
        //todo 按钮隐藏之类的
    }
}

function merge(flag, boxCode) {
    if (flag) {
        BootstrapDialog.confirm({
            title: "信息提示",
            message: "是否要执行退货入库操作?",
            btnCancelLabel: '返回',
            btnOKLabel: '确定',
            callback: function (result) {
                // 点击确定按钮时，result为true
                if (result) {
                    selectMergeBox(flag, boxCode);
                } else {
                    // 刷新父级页面
                    parent.location.reload();
                }
            }
        });
    } else {
        selectMergeBox(flag, boxCode);
    }
}

function selectMergeBox(flag, boxCode) {
    $('.merger-title').show();
    const opt = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/sale/order/return/list",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        async: false,
        success: function (data) {
            console.log("sd:" + JSON.stringify(data));
            if (data.code == 0) {
                initMergeBoxDetailList(data.data);
                // initOutBoxList(new Array());
            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}


//操作栏的格式化
function actionFormatter(value, row, index, field) {
    let result = '';
    console.log("row:" + JSON.stringify(row));
    // result += '<a href="javascript:;" class="btn btn-xs green" onclick="outOfStock(\'' + row.id + '\')" title="缺货"><span class="glyphicon glyphicon-pencil"></span></a>';
    result += '<button type="button" id="' + row.id + '_entry" class="btn btn-primary" onclick="returnEntryGoodsCollect(\'' + row.id + '\')">完成入库</button>';
    result += '&emsp;&emsp;<button type="button" id="' + row.id + '_loss" class="btn btn-warning" style="text-align: right;"  onclick="frmLossDone(\'' + row.id + '\')">报损</button>';
    return result;
}

//大件物品退货入库
function returnEntryGoodsCollect(id) {
    const orderRow = $('#merge-table-list').bootstrapTable('getRowByUniqueId', id);
    if (orderRow) {
        const boxCode = $('#merge-box-code').text();
        if (!boxCode) {
            BootstrapDialog.alert("货箱编号为空");
            return;
        }
        $('#ware-box-code').val(boxCode);
        $('#goods-box-code').val(boxCode);
        const opt = $("#form-param").serializeJSON();
        opt['detailList'] = Array.of(orderRow);
        console.log("销售退货入库:" + JSON.stringify(opt));
        //非空箱
        $.ajax({
            type: "POST",
            url: "/wcs/returnEntry",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(opt),
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {
                    $('#merge-table-list').bootstrapTable('removeByUniqueId', orderRow.id);
                } else {
                    BootstrapDialog.alert(data.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.responseJSON) {
                    if (XMLHttpRequest.responseJSON.msg) {
                        BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                    } else {
                        XMLHttpRequest.responseJSON.message
                    }
                }
            }
        });
    }
}

//退货商品列表
function initMergeBoxDetailList(saleOrderDetailList) {
    console.log(">>>>>>>>>>>" + JSON.stringify(saleOrderDetailList));
    $('#merge-table-list').bootstrapTable({
        data: saleOrderDetailList,
        method: 'post',
        pagination: false,//不分页
        sortable: false, //不排序
        sidePagination: "server",
        uniqueId: 'id',
        striped: true,
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            let temp = $("#search-condition").serializeJSON();
            return temp;
        },
        onLoadSuccess: function (data) {
            $("#merge-table-list").bootstrapTable("load", saleOrderDetailList);
        },
        columns: [{
            field: 'spuName',
            title: '商品',
            formatter: function (value, row, index) {
                return value + "(" + row.skuCode + ")";
            }
        }, {
            field: 'supplierCode',
            title: '供应商'
        }, {
            field: 'quantity',
            title: '数量'
        }, {
            field: 'weight',
            title: '每份重量',
            formatter: function (value, row, index) {
                return value.toFixed(2);
            }
        }, {
            field: 'shelfLife',
            title: '保质期',
            visible: false
        }, {
            field: 'temperatureCodeName',
            title: '温区名称'
        }, {
            field: 'temperatureCode',
            title: '温区编码',
            visible: false
        }, {
            field: 'spuId',
            title: '原料',
            visible: false
        }, {
            field: 'opt',
            title: '操作',
            align: 'center',
            valign: 'middle',
            formatter: actionFormatter,
        }]
    });
}


//原料报损
function frmLose() {
    $('#frm-lose-select').html('');
    let html = '';
    const boxList = $('#merge-table-list').bootstrapTable('getData');
    if (boxList && boxList.length > 0) {
        let flag = false;
        for (let i = 0; i < boxList.length; i++) {
            const boxDetail = boxList[i];
            // if (boxDetail.spuName && boxDetail.id) {
            if (boxDetail.id) {
                if (!flag) {
                    $('#goods-detail-id').val(boxDetail.id);
                }
                flag = true;
                html += '<option value="' + boxDetail.id + '" class="opt-frm-inf" style="height: 30px;padding-top: 5px;">' + boxDetail.spuName + '&nbsp;&nbsp;/&nbsp;&nbsp;' + boxDetail.weight + '</option>';
            }
        }
    }
    $('#frm-lose-select').append(html);
    $('#frm-lose-select').selectpicker('refresh');
    $('#frm-lose-model').modal({
        keyboard: false
    })
    sortWeightInfo("merge-table-list", sortWeightId, sortTyp, 1, null, 1);
}

//原料报损：取消/报损->false/true
function frmLoseClick(cancel) {
    if (cancel) {
        const id = $('#goods-detail-id').val();
        if (!id) {
            BootstrapDialog.alert("请选择报损原料");
            return;
        }
        const frmLoseWeight = $('#frm-lose-weight').val();
        if (!checkPrice(frmLoseWeight)) {
            BootstrapDialog.alert("输入重量格式不符");
            return;
        }
        const orderRow = $('#merge-table-list').bootstrapTable('getRowByUniqueId', id);
        console.log("合箱原料：" + JSON.stringify(orderRow));
        if (orderRow) {
            if (frmLoseWeight > orderRow.weight) {
                BootstrapDialog.alert("报损重量大于货箱内原料重量");
                return;
            } else {
                console.log("货箱信息更改前：" + JSON.stringify(orderRow));
                $('#merge-table-list').bootstrapTable('removeByUniqueId', id);
                orderRow.weight = parseFloat(orderRow.weight - frmLoseWeight).toFixed(2);
                console.log("货箱信息更改后：" + JSON.stringify(orderRow));
                insertRow(orderRow, 'merge-table-list', true);
            }
        } else {
            BootstrapDialog.alert("报损原料信息不存在");
            return;
        }
        $('#from-lose-goods-detail-box-code').val($('#merge-box-code').text());
        const opt = $("#form-frm-lose").serializeJSON();
        opt['clientId'] = $('#client-id').val();
        opt['boxCode'] = $('#merge-box-code').text();
        opt['type'] = 1;
        $.ajax({
            type: "POST",
            url: "/wcs/box/detail/updateFrmLoseById",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(opt),
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {
                    $('#frm-lose-model').modal('hide');
                } else {
                    BootstrapDialog.alert(data.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.responseJSON) {
                    if (XMLHttpRequest.responseJSON.msg) {
                        BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                    } else {
                        BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                    }
                }
            }
        });
    } else {
        console.log("2222222222222");
    }
}

//分拣称重socketIo响应
function electronicWeightCallBack(data) {
    console.log("称重数据返回：" + data);
    if (data) {
        const vc = JSON.parse(data);
        if (vc.weight) {
            sortWeightInfo("sort-spu-table", sortWeightId, sortTyp, 0, vc, 1);
        } else {
            console.log("分拣/报损称重异常：" + data);
        }
    }
}

//入库缓存位扫码响应
function pageEntryCallBack(data) {
    console.log("入库缓存位扫码响应：" + data);
    if (data) {
        const vc = JSON.parse(data);
        if (vc.code == 0) {
            const resultData = vc.data;
        }
    }
}

//仓库报损
function frmLossDone(id) {
    const ops = {};
    const opt = {};
    opt['saleOrderDetailId'] = id;
    ops['data'] = opt;
    BootstrapDialog.confirm({
        title: "信息提示",
        message: "是否要执行报损操作?",
        btnCancelLabel: '取消',
        btnOKLabel: '确认',
        callback: function (result) {
            // 点击确定按钮时，result为true
            if (result) {
                $.ajax({
                    type: "POST",
                    url: "/wcs/record/frm/loss/done",
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(ops),
                    dataType: "json",
                    success: function (data) {
                        if (data.code == 0) {
                            $('#merge-table-list').bootstrapTable('removeByUniqueId', id);
                        } else {
                            BootstrapDialog.alert(data.msg);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        if (XMLHttpRequest.responseJSON) {
                            if (XMLHttpRequest.responseJSON.msg) {
                                BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                            } else {
                                XMLHttpRequest.responseJSON.message
                            }
                        }
                    }
                });
            } else {
                // window.history.back();
            }
        }
    });
}